# string_extractor.py

from state import State
from event import Event
from action import Action
from pair import Pair

class StringExtractor:

    def __init__(self):
        self.current_state = State.LOOK_FOR_STRING
        self.result = []
        self.current_string = []

        # 状态转换表
        self.transitions = {
            (State.LOOK_FOR_STRING, Event.DOUBLE_QUOTATION): Pair(State.IN_STRING, Action.START_NEW_STRING),
            (State.LOOK_FOR_STRING, Event.OTHER_CHAR): Pair(State.LOOK_FOR_STRING, Action.IGNORE),
            (State.IN_STRING, Event.DOUBLE_QUOTATION): Pair(State.LOOK_FOR_STRING, Action.FINISH_CURRENT_STRING),
            (State.IN_STRING, Event.BACK_SLASH): Pair(State.COPY_NEXT_CHAR, Action.IGNORE),  # 进入转义字符处理
            (State.IN_STRING, Event.OTHER_CHAR): Pair(State.IN_STRING, Action.ADD_CURRENT_TO_STRING),
            (State.COPY_NEXT_CHAR, Event.OTHER_CHAR): Pair(State.IN_STRING, Action.ADD_CURRENT_TO_STRING)
        }

    def trigger(self, ch):
        event = Event.of(ch)
        pair = self.transitions.get((self.current_state, event), self.transitions.get((self.current_state, Event.OTHER_CHAR)))
        self.current_state = pair.state
        self.do_action(pair.action, ch)

    def do_action(self, action, current_char):
        if action == Action.IGNORE:
            return
        elif action == Action.START_NEW_STRING:
            self.current_string = []
        elif action == Action.ADD_CURRENT_TO_STRING:
            # 处理空格字符，只有在字符串已经包含内容时才保留空格
            if current_char != ' ' or self.current_string:
                self.current_string.append(current_char)
        elif action == Action.FINISH_CURRENT_STRING:
            # 只有非空字符串才添加到结果
            if self.current_string:
                self.result.append(''.join(self.current_string))
        elif action == Action.COPY_NEXT_CHAR:
            # 处理转义字符，将转义后的字符（例如\"）添加到字符串
            if current_char == '"':
                self.current_string.append('"')  # 转义后的双引号
            else:
                self.current_string.append(current_char)

    def get_result(self):
        return ''.join(self.result)  # 拼接并返回最终结果

